package gy.com.sansharescuesystem.utils;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;


/**
 * Created by zsf on 2017-07-13.
 */



public class HttpUtil {

    public static final String url ="http://dev.user.kfchain.com/api/";
    public static String sendByGet(String urlStr, Map<String, Object> params) throws IOException{
        if(params != null && params.size() > 0) {
            JSONObject jo = new JSONObject(params);
            urlStr = urlStr + "?params=" + URLEncoder.encode(jo.toString(), "UTF-8");
        }
        URL url = new URL(urlStr);
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

        urlConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");

        urlConnection.setRequestProperty("Accept", "application/json");

        urlConnection.setRequestMethod("GET");
        int statusCode = urlConnection.getResponseCode();

        BufferedReader br = null;
        if (statusCode == 200) {
            br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
            StringBuilder sb = new StringBuilder();
            String s = null;
            while((s = br.readLine())!=null){
                sb.append(s);
            }
            br.close();
            return sb.toString();
        } else {
            return null;
        }
    }

    public static String sendByPost(String urlStr, Map<String, Object> params) throws IOException{
        URL url = new URL(urlStr);
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");

        urlConnection.setRequestProperty("Accept", "application/json");

        urlConnection.setRequestMethod("POST");
        urlConnection.setDoOutput(true);
        OutputStream wr = urlConnection.getOutputStream();
        JSONObject jo = new JSONObject(params);
        wr.write(jo.toString().getBytes());
        int statusCode = urlConnection.getResponseCode();
        BufferedReader br = null;
        if (statusCode == 200) {
            br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
            StringBuilder sb = new StringBuilder();
            String s = null;
            while((s = br.readLine())!=null){
                sb.append(s);
            }
            br.close();
            wr.close();
            return sb.toString();
        } else {
            wr.close();
            return null;
        }
    }


}



